package com.iflytek.uoamp.agent.monitor.utils.ValidIP;
import com.iflytek.uoamp.agent.common.util.ReadAll;
import com.iflytek.uoamp.agent.common.util.WFile;
import com.iflytek.uoamp.agent.monitor.find.imp.baseitem.FindBaseMonitorItemAbs;
import com.iflytek.uoamp.agent.monitor.find.obj.NetWork;
import com.iflytek.uoamp.agent.monitor.utils.WinIPFinder;

import org.apache.commons.lang3.StringUtils;

import java.util.List;

public class WinValidIP implements ValidIPInterface {
	private String ip;
	public WinValidIP(String ip){
		this.ip = ip;
	}
	
	public String getIp() {
		return ip;
	}

	public void setIp(String ip) {
		this.ip = ip;
	}

	/**
	 * 判断当前ip信息是否在网卡信息里面
	 * @return
	 */
	@Override
	public boolean isOK(){
		List<NetWork> localNetWorks = WinIPFinder.findLocalIP();
		if(ip==null){
			return false;
		}
		
		for (NetWork curItem : localNetWorks) {
			if (curItem.getIp().equalsIgnoreCase(ip)){
				return true;
			}
		}
		
		return false;
	}
	
	/***
	 * 在配置ip不合法的情况下通过网卡信息尝试去获取本机的ip地址
	 */
	@Override
	public String guessIP(){
		List<NetWork> localNetWorks = WinIPFinder.findLocalIP();
		String ip = "";
		for (NetWork curItem : localNetWorks) {
			for (String validIPPrefix : FindBaseMonitorItemAbs.getSet()) {
				if (curItem.getIp().startsWith(validIPPrefix)) {
					ip = curItem.getIp();
					break;
				}
			}
			if (!StringUtils.isEmpty(ip)) {
				break;
			}
		}
		if(ip!=null && !ip.isEmpty()){
			WFile.wf("conf/monitor/clientIp", ip);
		} else {
			ip = ReadAll.readAll("conf/monitor/clientIp", "utf-8");
		}
		return ip;
	}
}
